<template>
	<div class="dynamic-panel">
		<div class="dynamic-panel-header">
			<el-row :gutter="8">
				<el-col :span="12">
					<el-button
						:type="active === 'future' ? 'primary' : ''"
						size="small"
						style="width: 100%"
						@click="onChangeType('future')"
						>未来 N 天</el-button
					>
				</el-col>
				<el-col :span="12">
					<el-button
						:type="active === 'past' ? 'primary' : ''"
						size="small"
						style="width: 100%"
						@click="onChangeType('past')"
						>过去 N 天</el-button
					>
				</el-col>
			</el-row>
		</div>
		<div>
			<el-input-number
				v-model="inputValue"
				:controls="false"
				:min="0"
				style="width: 100%"
				@blur="onInputBlur"
			></el-input-number>
		</div>
	</div>
</template>

<script setup>
	import { ref, onMounted } from 'vue'
	import { isNumber, isObject } from 'lodash-es'

	const props = defineProps(['initDate'])

	const active = ref('future')
	const inputValue = ref(0)

	const onChangeType = (type) => {
		active.value = type
	}

	const setValue = (obj) => {
		const offset = obj.offset
		if (offset === 0) {
			inputValue.value = 0
		} else if (offset > 0) {
			active.value = 'future'
			inputValue.value = offset
		} else {
			active.value = 'past'
			inputValue.value = -offset
		}
	}

	const getValue = () => {
		const val = inputValue.value
		if (val === 0) {
			return {
				type: 'dynamic',
				offset: val
			}
		}
		if (active.value === 'future') {
			return {
				type: 'dynamic',
				offset: val
			}
		} else {
			return {
				type: 'dynamic',
				offset: -val
			}
		}
	}

	const selectToday = () => {
		inputValue.value = 0
	}

	const selectYesterday = () => {
		active.value = 'past'
		inputValue.value = 1
	}

	const selectTomorrow = () => {
		active.value = 'future'
		inputValue.value = 1
	}

	const onInputBlur = () => {
		if (!isNumber(inputValue.value)) {
			inputValue.value = 0
		}
	}

	onMounted(() => {
		if (props.initDate && isObject(props.initDate)) {
			setValue({
				type: 'dynamic',
				offset: props.initDate.offset || 0
			})
		}
	})

	defineExpose({
		selectToday,
		selectYesterday,
		selectTomorrow,
		setValue,
		getValue
	})
</script>

<style scoped>
	.dynamic-panel {
		padding: 16px;
	}
	.dynamic-panel-header {
		padding-bottom: 8px;
	}
</style>
